package com.ifp.opengate.boot.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

/**
 * @desc AES 加密工具类
 * @author 灭霸 2018-11-05
 */
public class AESUtils {
    public static final String VIPARA = "0102030405060708";
    public static final String bm = "utf-8";

    public static String encrypt(String cleartext, String appSecret) throws Exception {
        String head = appSecret.substring(0, 8);
        String end = appSecret.substring(appSecret.length() - 8);
        appSecret = head + end;
        IvParameterSpec zeroIv = new IvParameterSpec(VIPARA.getBytes());
        SecretKeySpec key = new SecretKeySpec(appSecret.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
        byte[] encryptedData = cipher.doFinal(cleartext.getBytes(bm));

        return Base64.encodeBase64String(encryptedData);
    }

    public static String decrypt(String encrypted, String appSecret) throws Exception {
        String head = appSecret.substring(0, 8);
        String end = appSecret.substring(appSecret.length() - 8);
        appSecret = head + end;
        byte[] byteMi = Base64.decodeBase64(encrypted);
        IvParameterSpec zeroIv = new IvParameterSpec(VIPARA.getBytes());
        SecretKeySpec key = new SecretKeySpec(appSecret.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);
        byte[] decryptedData = cipher.doFinal(byteMi);

        return new String(decryptedData, bm);
    }
}